package com.tbit.config.sentinel;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.tbit.common.entity.view.Result;
import org.springframework.context.annotation.Configuration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * Sentinel限流响应处理
 *
 * @Author:BUGTian
 * @DATE: 2022/9/6
 */
@Configuration
public class SentinelExceptionHandler implements BlockExceptionHandler {

    private static final String HEADER = "Content-type";
    private static final String HEADER_VALUE = "application/json;charset:utf-8";
    private static final String CHARSET = "UTF-8";
    private static final String MSG = JSON.toJSONString(Result.errorMessage("操作频繁，请稍后再试", 429, null));

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        response.setHeader(HEADER, HEADER_VALUE);
        response.setCharacterEncoding(CHARSET);
        response.setStatus(429);
        PrintWriter out = response.getWriter();
        out.print(MSG);
        out.flush();
        out.close();
    }
}
